import utils from '../utils'
import {DouglasPeucker} from './index.js'

function simplify(dataset, opts) {
  const arcs = dataset.arcs
  if (!arcs || arcs.size() === 0) return // removed in v0.4.125: stop("Missing path data");
  opts = getStandardSimplifyOpts(dataset, opts) // standardize options
  internal.simplifyPaths(arcs, opts)

  // calculate and apply simplification interval
  if (opts.percentage || opts.percentage === 0) {
    arcs.setRetainedPct(utils.parsePercent(opts.percentage))
  } else if (opts.interval || opts.interval === 0) {
    arcs.setRetainedInterval(internal.convertSimplifyInterval(opts.interval, dataset, opts))
  } else if (opts.resolution) {
    arcs.setRetainedInterval(internal.convertSimplifyResolution(opts.resolution, arcs, opts))
  } else {
    // stop("Missing a simplification amount")
    utils.error('Missing a simplification amount')
  }

  internal.finalizeSimplification(dataset, opts)
}
function getStandardSimplifyOpts(dataset, opts) {
  opts = opts || {}
  return utils.defaults({
    method: getSimplifyMethod(opts),
    spherical: useSphericalSimplify(dataset.arcs, opts)
  }, opts)
}
function useSphericalSimplify(arcs, opts) {
  return !opts.planar && !arcs.isPlanar()
}
// Calculate simplification thresholds for each vertex of an arc collection
// (modifies @arcs ArcCollection in-place)
function simplifyPaths(arcs, opts) {
  const simplifyPath = internal.getSimplifyFunction(opts);
  arcs.setThresholds(new Float64Array(arcs.getPointCount())); // Create array to hold simplification data
  if (opts.spherical) {
    internal.simplifyPaths3D(arcs, simplifyPath);
    internal.protectWorldEdges(arcs);
  } else {
    internal.simplifyPaths2D(arcs, simplifyPath);
  }
  if (opts.lock_box) {
    internal.protectContentEdges(arcs);
  }
}
function getSimplifyMethod(opts) {
  let m = opts.method
  if (!m || m == 'weighted' || m == 'visvalingam' && opts.weighting) {
    m =  'weighted_visvalingam'
  }
  return m
}
function getSimplifyFunction(opts) {
  let f = null
  if (opts.method == 'dp') {
    f = DouglasPeucker.calcArcData
  } else if (opts.method == 'visvalingam') {
    f = Visvalingam.getEffectiveAreaSimplifier(opts.spherical)
  } else if (opts.method == 'weighted_visvalingam') {
    f = Visvalingam.getWeightedSimplifier(opts, opts.spherical)
  } else {
    // stop('Unsupported simplify method:', method)
    utils.error(`Unsupported simplify method:${method}`)
  }
  return f
}
export default {
  simplify,
}